package com.landi.carkey.manager;

import com.avos.avoscloud.AVObject;
import com.landi.carkey.application.CarKeyApplication;
import com.landi.carkey.greendao.DaoMaster;
import com.landi.carkey.greendao.DaoSession;
import com.landi.carkey.greendao.KeyModel;
import com.landi.carkey.greendao.KeyModelDao;
import com.landi.carkey.interfaces.IDialogTimeoutListener;
import com.landi.carkey.util.DateUtil;

import java.util.Date;
import java.util.List;

/**
 * @Description {具体做什么}
 * @Creator wushan
 * @Date 2016/12/1 21:34
 */

public class GreenDaoManager {

    private static GreenDaoManager mInstance;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    public static final String TABLE_NAME = "KeyModel";
    public static final String FILED_NUMBER = "number";
    public static final String FILED_PASSWORD = "passWord";
    public static final String FILED_ClOUDID = "cloudId";
    public static final String FILED_CONTRIBUTOR = "contributor";
    public static final String FILED_CITY = "city";


    public GreenDaoManager() {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(CarKeyApplication.getInstance(), "notes-db", null);
        DaoMaster mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
    }

    public static GreenDaoManager getInstance() {
        if (mInstance == null) {
            mInstance = new GreenDaoManager();
        }
        return mInstance;
    }

    public DaoMaster getMaster() {
        return mDaoMaster;
    }

    public DaoSession getSession() {
        return mDaoSession;
    }

    public DaoSession getNewSession() {
        mDaoSession = mDaoMaster.newSession();
        return mDaoSession;
    }

    public void upDataLocalDataBase(List<AVObject> todos, IDialogTimeoutListener listener) {

        for (int i = 0; i < todos.size(); i++) {

            AVObject av = todos.get(i);
            String cloudid = av.getObjectId();
            String number = av.getString(FILED_NUMBER);
            String password = av.getString(FILED_PASSWORD);
            Date date = av.getUpdatedAt();
            String contributor  =  av.getString(FILED_CONTRIBUTOR);
            String city = av.getString(FILED_CITY);

            List<KeyModel> list = mDaoSession.getKeyModelDao().queryBuilder().where(KeyModelDao.Properties.Number.eq(number),
                    KeyModelDao.Properties.PassWord.eq(password)).build().list();
            if (list!=null&&list.size()>0){
                continue;
            }else{//Add
               long id = mDaoSession.getKeyModelDao().insert(new KeyModel(null,number,password,
                       DateUtil.getFormatDateTime(date, "yyyy-MM-dd HH:mm:ss"),cloudid,contributor,null,city));
            }
        }

        listener.onDialogTimeout("");

    }

}
